package com.example.rbac.controller;

import com.example.rbac.common.Result;
import com.example.rbac.model.User;
import com.example.rbac.model.dto.UserInfoDTO;
import com.example.rbac.service.UserService;
import com.example.rbac.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping
@Api(tags = "用户认证")
public class AuthController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private JwtUtils jwtUtils;
    
    @PostMapping("/register")
    @ApiOperation("用户注册")
    public Result<?> register(@RequestBody User user) {
        userService.register(user);
        return Result.success("注册成功");
    }
    
    @PostMapping("/login")
    @ApiOperation("用户登录")
    public Result<?> login(@RequestBody Map<String, String> loginInfo) {
        String username = loginInfo.get("username");
        String password = loginInfo.get("password");
        
        // 用户登录，生成token
        String token = userService.login(username, password);
        
        // 获取用户信息并脱敏
        User user = userService.getUserByUsername(username);
        UserInfoDTO userInfo = new UserInfoDTO();
        userInfo.setId(user.getId());
        userInfo.setUsername(user.getUsername());
        userInfo.setNickname(user.getNickname());
        userInfo.setEmail(user.getEmail());
        userInfo.setPhone(user.getPhone());
        userInfo.setAvatar(user.getAvatar());
        userInfo.setStatus(user.getStatus());
        userInfo.setRoles(userService.getRolesByUserId(user.getId()));
        userInfo.setPermissions(userService.getPermissionsByUserId(user.getId()));
        
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("userInfo", userInfo);
        
        return Result.success(result);
    }
    
    @PostMapping("/logout")
    @ApiOperation("用户登出")
    public Result<?> logout(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token != null) {
            userService.logout(token);
        }
        return Result.success("登出成功");
    }
}